package com.test.transaction.demo;

import java.util.Properties;

import javax.sql.DataSource;

import org.apache.ibatis.datasource.pooled.PooledDataSourceFactory;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.support.TransactionTemplate;

@Configuration
@MapperScan(basePackages = {"com.test.mapper"}, sqlSessionFactoryRef="sqlSessionFactory")
public class DataSourceConfiguration {

    @Bean(name = "dataSource")
    @Primary
    public DataSource setDataSource() {
    	PooledDataSourceFactory factory = new PooledDataSourceFactory();
    	Properties properties = new Properties();
    	properties.setProperty("driver", "com.mysql.jdbc.Driver");
    	properties.setProperty("url", "jdbc:mysql://10.16.9.34:3306/sms_crm_db");
    	properties.setProperty("username", "dev_sms");
    	properties.setProperty("password", "ziroomdb");
    	factory.setProperties(properties);
        return factory.getDataSource();
    }

    @Bean(name = "sqlSessionFactory")
    public SqlSessionFactory setSqlSessionFactory(@Qualifier("dataSource") DataSource dataSource) throws Exception {
        // 通过Mybatis Spring模块提供的SqlSessionFactoryBean
        // 创建Mybatis的SqlSessionFactory对象
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setTypeAliasesPackage("com.test.po");
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:com/test/mapper/*.xml"));
        return bean.getObject();
    }

    @Bean
    // 事务管理器
    public DataSourceTransactionManager transactionManager(@Qualifier("dataSource") DataSource dataSource){//事务管理
    	return new DataSourceTransactionManager(dataSource);
	}

    @Bean
    // 事务模板
    public TransactionTemplate transactionTemplate(PlatformTransactionManager platformTransactionManager){
    	return new TransactionTemplate(platformTransactionManager);
	}

}
